package com.tsfyun.scm.gateway.config;

import com.tsfyun.scm.gateway.config.properties.NoRequestLimitProperties;
import com.tsfyun.scm.gateway.config.properties.PermitUrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;


/**
 * @Description:
 * @CreateDate: Created in 2020/11/10 15:44
 */
@Configuration
@Slf4j
public class RateLimitKeyConf {


    /**
     * ip限流
     * @return
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }


    /**
     * 用户限流
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }

    /**
     * 路径限流
     * @return
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 自定义键
     * @param permitUrlProperties
     * @param noRequestLimitProperties
     * @return
     */
    @Bean
    @Primary
    public KeyResolver customKeyResolver(final PermitUrlProperties permitUrlProperties,final NoRequestLimitProperties noRequestLimitProperties) {
        CustomKeyResolver customKeyResolver = new CustomKeyResolver(permitUrlProperties,noRequestLimitProperties);
        return customKeyResolver.customKeyResolver();
    }

}
